package com.ruoyi.weixin.config;

import com.ruoyi.common.config.Global;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.YamlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

public class WxGlobal {
    private static final Logger log = LoggerFactory.getLogger(Global.class);

    private static String NAME = "application.yml";

    /**
     * 当前对象实例
     */
    private static WxGlobal global;

    /**
     * 保存全局属性值
     */
    private static Map<String, String> map = new HashMap<String, String>();

    private WxGlobal()
    {
    }

    /**
     * 静态工厂方法
     */
    public static synchronized WxGlobal getInstance()
    {
        if (global == null)
        {
            global = new WxGlobal();
        }
        return global;
    }

    /**
     * 获取配置
     */
    public static String getConfig(String key)
    {
        String value = map.get(key);
        if (value == null)
        {
            Map<?, ?> yamlMap = null;
            try
            {
                yamlMap = YamlUtil.loadYaml(NAME);
                value = String.valueOf(YamlUtil.getProperty(yamlMap, key));
                map.put(key, value != null ? value : StringUtils.EMPTY);
            }
            catch (FileNotFoundException e)
            {
                log.error("获取全局配置异常 {}", key);
            }
        }
        return value;
    }

    /**
     * 获取appid
     */
    public static String getAppId()
    {
        return StringUtils.nvl(getConfig("wx.miniapp.configs.appid"), "wx9ea8816ee1434159");
    }

    /**
     * 获取Secret
     */
    public static String getSecret()
    {
        return StringUtils.nvl(getConfig("wx.miniapp.configs.secret"), "1f469d120d2dfaf9b3b0f2f545361e66");
    }

    /**
     * 获取Token
     */
    public static String getToken()
    {
        return StringUtils.nvl(getConfig("wx.miniapp.configs.token"), "cloudoer");
    }

    /**
     * 获取AesKey
     */
    public static String getAesKey()
    {
        return StringUtils.nvl(getConfig("wx.miniapp.configs.aesKey"), "OLa89F5M0EXY7ZcHOStvDPNEHZk84afwgUR4qq282lE");
    }

    /**
     * 获取MsgDataFormat
     */
    public static String getMsgDataFormat()
    {
        return StringUtils.nvl(getConfig("wx.miniapp.configs.msgDataFormat"), "JSON");
    }
}
